package temp;

public class CircularBuffer {

	private byte[] buffer;
	/*aponta para a primeira posicao do buffer, se o buffer estiver vazio start=-1*/
	private int start;
	/*aponta para proxima posicao livre(se houver),se o buffer estiver vazio end=0,se tiver cheio end=start*/
	private int end;
	
	
	
	public int capacity(){
		if(start > end){
			return start-end;
		}else{
			return buffer.length - (end-start);
		}
	}
	
	public boolean isEmpty(){
		return start==-1;
	}
	
	public void clear(){
		start = -1;
		end = 0;
	}
	

	public int write(byte[] data){		
		return write(data,0,data.length);
	}
	
	public int write(byte[] data,int position,int length){
		int writed = length > capacity()? capacity():length;

		for(int i = 0 ; i < writed;i++){
			buffer[(end + i)%buffer.length] = data[i + position];
		}
		
		end = (end + writed)%buffer.length;
		return writed;
	}
	
	public int read(byte[] out){
		return read(out,0,out.length);
	}
	
	public int read(byte[] out,int position, int length){
		int readed = length > (buffer.length - capacity())?buffer.length - capacity():length;
		
		for(int i = 0 ; i < readed;i++){
			out[i + position] = buffer[(start + i)%buffer.length];
		}
		start = (start + position) % buffer.length;
		
		if(start == end){
			clear();
		}
		return readed;
	}
}
